package com.yc.navy.dayfresh.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.navy.dayfresh.entity.Fav;
import com.yc.navy.dayfresh.entity.TagFav;
import com.yc.navy.dayfresh.mapper.FavMapper;
import com.yc.navy.dayfresh.mapper.TagFavMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class TagBiz {
    @Autowired
    private TagFavMapper tagFavMapper;

    @Autowired
    private FavMapper favMapper;

    @Transactional
    public void mergeTags(Integer sourceTagId, Integer targetTagId) {
        // 1. 获取被合并的标签的所有链接
        List<Fav> sourceFavs = favMapper.selectFavByTid(sourceTagId);

        // 2. 获取目标标签的当前所有链接
        List<Fav> targetFavs = favMapper.selectFavByTid(targetTagId);
        Set<Integer> targetFavIds = new HashSet<>();
        for (Fav fav : targetFavs) {
            targetFavIds.add(fav.getId());
        }

        // 3. 合并源标签中的链接到目标标签，避免重复
        for (Fav sourceFav : sourceFavs) {
            if (!targetFavIds.contains(sourceFav.getId())) {
                TagFav tagFav = new TagFav();
                tagFav.setTid(targetTagId);
                tagFav.setFid(sourceFav.getId());
                tagFavMapper.insert(tagFav);
            }

            // 4. 从源标签中移除与该链接的关系
            tagFavMapper.delete(new LambdaQueryWrapper<TagFav>()
                    .eq(TagFav::getTid, sourceTagId)
                    .eq(TagFav::getFid, sourceFav.getId()));

            // 5. 更新 Favorite 表中的 tags 字段
            Fav favToUpdate = sourceFav;
            String currentTags = favToUpdate.getTags(); // 当前的 tags 字段
            String updatedTags = removeTagFromTags(currentTags, sourceTagId); // 移除源标签 ID
            favToUpdate.setTags(updatedTags);
            favMapper.updateById(favToUpdate); // 更新 Fav 表
        }
    }
    // 辅助方法：移除指定标签 ID
    private String removeTagFromTags(String currentTags, Integer tagIdToRemove) {
        if (currentTags == null || currentTags.isEmpty()) {
            return currentTags;
        }
        // 假设 tags 是逗号分隔的字符串
        String[] tagsArray = currentTags.split("[,;，；]+");
        StringBuilder updatedTags = new StringBuilder();
        for (String tag : tagsArray) {
            if (!tagIdToRemove.toString().equals(tag.trim())) {
                if (updatedTags.length() > 0) {
                    updatedTags.append(";");
                }
                updatedTags.append(tag.trim());
            }
        }
        return updatedTags.toString();
    }
}
